<template>
  <div class="post-detail">

    <van-nav-bar
        title="详情"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <!-- 帖子详情头部 -->
    <div class="scroll-container">
      <div class="item" v-if="post1">
        <div class="item-header">
          <div class="item-header-left">
            <van-image :src="post1.authorImageUrl" round width="40" height="40"/>
            <div class="header-info">
              <span class="item-header-name">{{ post1.authorUsername }}</span>
              <span class="item-header-time">{{ post1.createTime }}</span>
            </div>
          </div>
          <van-tag type="primary" round size="small" v-if="post1.hot">hot</van-tag>
        </div>
        <div class="item-content">
          <p>{{ post1.content }}</p>
          <div class="image-wrapper">
            <van-image :src="post1.contentImg" width="200px" height="100px"/>
          </div>
          <div class="item-footer">
            <van-icon name="like-o" size="16" class="icon"/>
            <span class="icon-text">{{ post1.praises }}</span>
            <van-icon name="star-o" size="16" class="icon"/>
            <span class="icon-text">{{ post1.collect }}</span>
            <van-icon name="chat-o" size="16" class="icon"/>
            <span class="icon-text">{{ post1.review }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-section">
      <div class="comment-item" v-for="(comment, index) in comments" :key="index">
        <van-image :src="comment.imageUrl" class="comment-avatar" ></van-image>
        <div class="comment-body">
          <div class="info">
            <div class="name">{{ comment.username }}</div>
            <div class="date">{{ comment.reviewTime }}</div>
          </div>
          <div class="content">{{ comment.content }}</div>
        </div>
      </div>
    </div>


    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <van-button round type="primary" size="small" icon="edit" class="comment-btn"  @click="openDialog">添加评论</van-button>

      <van-dialog v-model:show="dialogVisible" title="评论内容" show-cancel-button>
        <van-cell-group inset>
          <van-field
              v-model="comment"
              rows="2"
              autosize
              label="留言"
              type="textarea"
              maxlength="50"
              placeholder="请输入留言"
              show-word-limit
          />
        </van-cell-group>
        <template #footer>
          <van-button @click="closeDia">取消</van-button>
          <van-button type="primary" @click="submitCircle">确认</van-button>
        </template>
      </van-dialog>

      <div class="icon-group">
        <van-icon name="like-o" size="16" color="#f44336" @click="praisesPost"/>
        <span class="num">{{ post1.praises }}</span> <!-- 绑定评价数 -->
        <van-icon name="star-o" size="16" color="#f44336" @click="collectPost"/>
        <span class="num">{{ post1.collect}}</span> <!-- 绑定浏览数 -->
        <van-icon name="chat-o" size="16" color="#f44336"/>
        <span class="num">{{ post1.review  }}</span> <!-- 绑定收藏数 -->
      </div>
    </div>
  </div>





</template>

<script setup>
import {ref, onMounted} from 'vue';
import {get, post} from "../../util/request.js";
import {useRoute} from 'vue-router';


const comment = ref('');
const closeDia = () => {
  dialogVisible.value = false;
  comment.value = '';
};
const onClickLeft = () => history.back();
const loading = ref(false);
const finishedText = ref('没有更多了');
const errorText = ref('加载失败，请稍后重试');

const dialogVisible = ref(false);
// 定义数据存储评论列表和帖子详情


// 获取路由参数中的ID
const route = useRoute();
const id = route.params.id; // 假设ID作为路由参数传递


const openDialog = () => {
  dialogVisible.value = true;
};
const post1 = ref([]);
// 示例评论数据
const comments = ref([]);

const userInfo = ref([])

onMounted(() => {
  fetchData(); // 组件挂载后立即发起请求

  fetchComments();
});

// 发起请求获取帖子详情和评论
const fetchData = async () => {
  try {
    const response = await get(`circle/selectById/${id}`);
    // 假设API返回的数据结构包含了帖子详情(list)和评论(comments)
    post1.value = response.data;
    if (post1.value.userId) {
      const userDataResponse = await get(`user/user/selectUser/${post1.value.userId}`);

      // 提取并合并需要的字段到post1对象中
      if (userDataResponse.data && userDataResponse.data.username && userDataResponse.data.imageUrl) {
        post1.value.authorUsername = userDataResponse.data.username; // 更新用户名
        post1.value.authorImageUrl = userDataResponse.data.imageUrl; // 更新头像图片URL
      } else {
        console.warn("Expected fields missing in the user data response.");
      }
    } else {
      console.warn("UserId not found in the post data.");
    }
  } catch (error) {

    // 可以在这里处理错误情况，比如设置错误文本给用户提示
  }
};

const fetchComments = async () => {
  try {
    const response = await get('study/review/findCircle', {
      // 假设需要传递文章ID来获取特定文章的评论，根据实际情况调整
      circleArticleId: route.params.id
    });

    if (response.data.code === 0) {
      comments.value = response.data.data;   // 假定返回的数据直接是评论数组
      console.log('评论获取成功', response.data.data);
      //遍历返回得到的评论数组
      for (let i = 0; i < comments.value.length; i++) {
        const comment = comments.value[i];
         await get(`user/user/selectUser/${comment.userId}`).then(res=>{
           if(res.code===0){
             userInfo.value.push(res.data)
             comments.value[i].imageUrl=res.data.imageUrl
             comments.value[i].username=res.data.username
             console.log(userInfo.value)
           }else{
             console.log(res.data.msg)
           }

         });
        // if (response.data.code === 0) {
        //   const userData = response.data.data;
        //   comment.authorUsername = userData.username;
        //   comment.authorImageUrl = userData.imageUrl;
        //   console.log(comment);
        // } else {
        // }
      }

    } else {
      console.error('Failed to fetch comments', response.data.msg);
    }
  } catch (error) {
    console.error('Error fetching comments', error);
  }
 }



const submitCircle = (async () => {
  try {


    // 发送POST请求到服务器，这里假设的URL路径和请求体格式需要根据你的后端API进行调整
    const response = await post('study/review/commentCircle', {
      circleArticleId : id,
      content:comment.value
    });
    // 在评论成功后发送新的请求
    const reviewResponse = await post('circle/addReview', {id : id});
    if (response.data.code === 0 && reviewResponse.data.code === 0) { // 通常成功的HTTP状态码为200或201
      // 请求成功，可以在此处处理成功后的逻辑，例如弹出成功提示、清空表单等
      console.log('评论提交成功');
      closeDia(); // 关闭对话框
      comment.value = ''; // 清空评论内容
      // 刷新页面数据，可以调用fetchData和fetchComments方法，但请注意这会导致整个页面数据重新加载
      fetchData();
      fetchComments();
    } else {
      console.error('评论提交失败，服务器响应状态码：', response.status);
    }
  } catch (error) {
    console.error('评论提交时发生错误：', error);
  }
});


const  praisesPost = async () => {
  try {
    const response = await post(`circle/addPraises/${id}`);
    if (response.data.code === 0) {
      alert('点赞成功');
      // 获取最新的关注数
      const rs = await fetchLike(id);
      // 更新组件中的收藏数
      post1.value.praises = rs.praises;
    } else {
      alert('关注失败');
    }
  } catch (error){
  }
};

const fetchLike = async (id) => {
  try {
    const response = await get(`circle/praises/${id}/praises`);
    const praises = response.data.data.praises;
    return praises;// 假设后端返回的数据结构中有一个字段叫做 likes
  } catch (error) {
    console.error('获取点赞数异常：', error);
    return 0; // 出错时返回默认值
  }
};



const collectPost = async () => {
  try {
    const response = await post(`circle/addCollect/${id}`);
    if (response.code === 0) {
      alert('收藏成功');
      // 获取最新的收藏数
      const rs = await fetchCollect(id);
      // 更新组件中的收藏数
      post1.value.collect = rs.collect;
    } else {
      alert('收藏失败');
    }
  } catch (error) {
    console.error('收藏请求异常：', error);
  }
};


const fetchCollect = async (id) => {
  try {
    const response = await get(`circle/collect/${id}/collect`);
    const collect = response.data.collect;
    return collect;// 假设后端返回的数据结构中有一个字段叫做 likes
  } catch (error) {
    console.error('获取收藏数异常：', error);
    return 0; // 出错时返回默认值
  }
};





</script>

<style scoped>
.post-detail {
  /* 根据需要添加全局样式 */
}

.header {
  display: flex;
  align-items: center;
  padding: 10px;
}

.user-info {
  margin-left: 10px;
  display: flex;
  align-items: center;
}

.date {
  margin-left: auto;
}

.comment-section {
  /* 添加评论区域的样式 */
}

.comment-item {
  display: flex;
  align-items: start;
  margin-bottom: 10px;
  padding: 10px;
  border-bottom: 1px solid #ebebeb;
}

.interactions {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.num {
  margin-left: 5px;
}

.bottom-bar {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使元素在行内两端对齐 */
  padding: 10px;
  width: 100%; /* 确保底部栏适应容器宽度 */
}

.icon-group {
  display: flex;
  align-items: center; /* 使图标和数字垂直居中对齐 */
}

.comment-btn {
  margin-right: auto; /* 将按钮推到左侧，其他图标自动排列在右侧 */
}



/* 在已有样式基础上新增或调整 */
.item-header-left {
  display: flex;
  flex-direction: column; /* 使得时间在用户名下方 */
  align-items: center; /* 可选，根据需要对齐内容 */
}

.header-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 或其他对齐方式 */
}



/* 调整评论头像尺寸 */
.comment-avatar {
  width: 40px !important;
  height: 40px !important;
}
</style>